<?php
	require '../../include/library.inc.php';
	require '../../include/admin_login.inc.php';
	require '../../include/paging.inc.php';
	
	
	$sql_lang = 'SELECT lang_id,Name,code FROM language WHERE published ';	
		
	if (!isset($_POST['is_submitted'])) {
		$_POST['is_submitted'] = '';
	}
	if (!isset($error_message)) {
		$error_message = '';
	}	
	$team_id = $_GET["team_id"];

if($_POST["redirect"] || $_SESSION['redirect'] ){
	if($_POST["redirect"]) $redirect = $_POST["redirect"];
	if($_SESSION['redirect']){ 
	$redirect = $_SESSION['redirect'];
	unset($_SESSION['redirect']);
	}
}else{
       $redirect = $_SERVER['HTTP_REFERER'];	
     }
	
	if ($_POST['is_submitted']) {
		$error_message = '';
		$redirect = $_POST["redirect"];
    
	$result_lang = query($sql_lang);
	while ($row_lang = mysql_fetch_object($result_lang)) {
	
		if (!$_POST['title'][$row_lang->lang_id])  $error_message .= 'Не е въведено заглавие на '.$row_lang->Name.'<br/>';
		
		
		if (!$_POST['sef_url'][$row_lang->lang_id])
		{
			$error_message .= 'Не е въведен SEF URL на '.$row_lang->Name.'<br/>';
		}else{
			
		 if(!preg_match('/^[0-9A-Za-z\p{Cyrillic}\-\_]+$/u', $_POST['sef_url'][$row_lang->lang_id])) 						            $error_message .= 'Въведеният SEF URL е невалиден<br/>';
			$sql = "SELECT id FROM sef_url WHERE sef_url = '".$_POST['sef_url'][$row_lang->lang_id]."' AND query != '".$team_id."' ";
			$result = query($sql);
			if ($row_seo = mysql_fetch_object($result)) $error_message .= 'Въведеният SEF URL на '.$row_lang->Name.' вече е използван<br/>';
		}
	
	}
	
	
	
    if(!$error_message) {
		
		//Update DB
		$sql = "UPDATE team SET
				 
				
				published = '".intval($_POST['published'])."'
				 
				 WHERE
				 team_id = '$team_id'
				";
		query($sql);

		$result_lang = query($sql_lang);
		$lang_num = 0;
		while ($row_lang = mysql_fetch_object($result_lang)) {
		
			$sql = "UPDATE team_description SET
					 title = 		 '".escape($_POST['title'][$row_lang->lang_id])."',
					 meta_description = 		 '".escape($_POST['meta_description'][$row_lang->lang_id])."', 
					 description = '".escape($_POST['description'][$row_lang->lang_id])."'
				WHERE
					 team_id = '".$team_id."'
					 AND
					 lang_id = '".$row_lang->lang_id."'
				  ";
				
			query($sql);
		
			
			$sql = "UPDATE sef_url SET
					 sef_url = 		 '".escape($_POST['sef_url'][$row_lang->lang_id])."'
				  WHERE
				  	tamplate = 'testimonial'
				  AND
					query = '".$team_id."'
				  AND
					lang_id = '".$row_lang->lang_id."'
				  ";
				 
			query($sql);
			$lang_num++;
		}
		if($_FILES['cover']['tmp_name']){
			
			$upload_path = "../team_images/";
			if (is_uploaded_file($_FILES['cover']['tmp_name'])) {
						
						$tmp_file = $_FILES['cover']['tmp_name'];
						$exp = explode('.',$_FILES['cover']['name']);
						$img_type = strtolower(end($exp));
						$new_name = $_POST['sef_url'][$lang_num].".".$img_type;
						
						include '../../include/image_man.php';
						$imn = new ImageManipulator;
						$imn -> decider($img_type,$tmp_file);
						
						if(copy($tmp_file.'_image', $upload_path.'big/'.$new_name) && copy($tmp_file.'_thumb', $upload_path.'covers/'.$new_name)) {
						
							$sql = "UPDATE team SET
										cover = '$new_name'
									WHERE team_id = '$team_id'";
							query($sql);
							
						} else{
							$_SESSION['message'] .= 'Грешка при качване на снимка. ';
						}			
						
				}
		}
		
		if($_POST['project_id'])
		{
			
			$sql = "DELETE FROM 
              team_to_project
            WHERE
              team_id = '$team_id'
			   
			   
             ";
    		query($sql);
			
			$project_id = $_POST['project_id'];
		  
			foreach ($project_id as $key => $value) {
			
				$sql = 'INSERT INTO team_to_project
							  (team_id,project_id)
							VALUES
							  ('.$team_id.','.intval($value).')
							  ';
				query($sql);
			
			}
		}
		
		
		
		$_SESSION['message'] .= 'Редакцията е успешна!';
        
		if($_POST["redirectForm"]){
           redirect($_POST["redirectForm"]);
		}else{
			$_SESSION['redirect'] = $redirect;
		   redirect(HTML_BASE_ADMIN.'testimonial_edit.php?team_id='.$team_id);
		   
		   
		}
    }
	
	
	
	
	
}else{
  	$sql = "SELECT 
			
			cover,
			published
		FROM
			team
		WHERE
			team_id ='".$team_id."'
		
		";
	$result_cat = query($sql);
	$row_cat = mysql_fetch_object($result_cat);
	$_POST['published'] =  $row_cat->published;
	$_POST['category'] =  $row_cat->category;
	$_POST['cover'] =  $row_cat->cover;
	if (!$row_cat) redirect("team.php");
	
}
	

	
	head_admin("Редактиране");
?>

<script type="text/javascript" src="<?=HTML_BASE_ADMIN?>js/calendarDateInput.js"></script>
<script type="text/javascript" src="<?=HTML_BASE_ADMIN?>tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
	// General options
	language : "bg", 
	mode : "exact",
    elements : "body1,body2,body3,body4,body5",
	theme : "advanced",
	relative_urls : false,
	plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager",

	// Theme options
	theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect",
	theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
	theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen,|,image,insertimage",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	theme_advanced_statusbar_location : "bottom",
	theme_advanced_resizing : false,

	
	
});
</script>
		
            <?php if ($error_message) { ?>
			<div class="message red">
				<h3>Грешка!</h3>
				<?=$error_message?>
			</div>
			<?php } ?>
			
            <div class="topbuttons">
            	<a href="<?=$redirect?>">Обратно</a>
            </div>
			
            <h3>Редактиране</h3>

     
     
             
            
<form id="page_team_form_id" action="<?=$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']?>" method="post" enctype="multipart/form-data">
            <input type="hidden" name="is_submitted" value="1" />
			<input type="hidden" name="redirect" value="<?=$redirect?>" />
             <input id="redirectForm" type="hidden" name="redirectForm" value="" />
            
            
		
<?php 
			
			$sql = 'SELECT 
						lang_id,
						Name,
						code
						
					FROM
						language
					WHERE
						published
					
					';
			$result = query($sql);
			
			$i=0;
			
			?>
				
 
			
	<div id="tabs">
        
        	<ul id="tabs-ui">
           
			</ul>
			
			
			<?php
			$tabs="";
			$result_lang = query($sql_lang);
			while ($row_lang = mysql_fetch_object($result)) {
					
				  $tabs.=' <li><a href="'.$_SERVER['PHP_SELF'].'?team_id='.$team_id.'#tabs-'.$row_lang->lang_id.'">'.$row_lang->Name.'</a></li>';

					
			if (!$_POST['is_submitted']) {
				
				
					$sql_d = "SELECT *	FROM team_description
					WHERE
						team_id = '".$team_id."'
						AND 
						lang_id = '".$row_lang->lang_id."'
					";
					$result_d = query($sql_d);
					$row_d = mysql_fetch_object($result_d);
					
					$_POST['title'][$row_lang->lang_id] =  $row_d->title;
					$_POST['description'][$row_lang->lang_id] =  $row_d->description;
					$_POST['meta_description'][$row_lang->lang_id] =  $row_d->meta_description;
					
					
					$sql_s = "SELECT sef_url	FROM sef_url
					WHERE
						tamplate = 'testimonial'
						AND
						query = '".$team_id."'
						AND 
						lang_id = '".$row_lang->lang_id."'
					";
					$result_s = query($sql_s);
					$row_s = mysql_fetch_object($result_s);
					$_POST['sef_url'][$row_lang->lang_id] = $row_s->sef_url;
					
			}
			
			$sef_img = $_POST['sef_url'][$row_lang->lang_id];
								  
			?>
            	
		
              
            <div id="tabs-<?=$row_lang->lang_id?>">
             <dl class="clearfix">
                <h3>Данни на  <?=$row_lang->Name?></h3>
                
                <dt><label class="required">Линк <?=$row_lang->Name?>:</label>
        <?=HTML_BASE?><input  class="sef_url" id="sef_url_<?=$row_lang->lang_id?>"  name="sef_url[<?=$row_lang->lang_id?>]" type="text" value="<?=$_POST['sef_url'][$row_lang->lang_id]?>" >
        </dt>	
                
                
                <dt><label class="required">Заглавие на <?=$row_lang->Name?></label></dt>
                <dd><input class="inputbox w500" id="title_<?=$row_lang->lang_id?>" name="title[<?=$row_lang->lang_id?>]" type="text" value="<?=$_POST['title'][$row_lang->lang_id]?>" ></dd>
                <dt><label >Кратко описание на <?=$row_lang->Name?>(до 110 символа)</label></dt>
                <dd><textarea class="inputbox w500" name="meta_description[<?=$row_lang->lang_id?>]" rows="3" maxlength="110"><?=$_POST['meta_description'][$row_lang->lang_id]?></textarea></dd>
                <dt><label>Описание на <?=$row_lang->Name?></label></dt>
                <dd><textarea id="body<?=$row_lang->lang_id?>"  class="inputbox" style="width:100%" name="description[<?=$row_lang->lang_id?>]" rows="16"><?=sth($_POST['description'][$row_lang->lang_id])?></textarea></dd>
                
                
		    </dl>
                     <script>
					 	
						$("#title_<?=$row_lang->lang_id?>").keyup(function(){
							
							$("#sef_url_<?=$row_lang->lang_id?>").val(convertToSlug($(this).val()));
						});
						$("#sef_url_<?=$row_lang->lang_id?>").keyup(function(){
							
							$("#sef_url_<?=$row_lang->lang_id?>").val(convertToSlug($(this).val()));
						});
					 </script>
           </div>
                        
            
		 <?php
				
			}
			
			
	  	  ?>
          
           </div>
			<dl class="clearfix" >
            
                <dt>
                    <label class="required">Корица на проекта 
                    </label>
                </dt>
                <dd>
                    <input class="inputbox w250" name="cover" type="file" accept="image/*" />
                </dd>
            	<img src="../team_images/covers/<?=$_POST['cover']?>"/>
                
                	<dl class="clearfix" >	
		
            
				<dd style="float:left;"><input class="checkbox" name="published" id="published" type="checkbox" value="1" <?=(($_POST['published'])?"checked=\"checked\"":"")?> />
				<label>Публикуван</label></dd>
            
			 <dl>
   			<dt>
      			<label >Проекти</label>
    		</dt>
    		<dd>
				<ul class="type-box">
				<?php         
                    $sql_c = "SELECT
                    c.project_id,
                    d.title
                    
                FROM
                    projects AS c,
                    project_description AS d
                WHERE
                
                    c.project_id = d.project_id
                    
                    AND
                    
                    d.lang_id = '1'
                    
                    AND
                    c.published
					AND type = 'project'
                    
                    ORDER BY c.order_number DESC
                    
                  ";
                
                    $result_c = query($sql_c);
                    $i = 1;	
                    while ($row = mysql_fetch_object($result_c)) {
                          ?>
                        <li>
                          <label>
                            <input class="checkbox" name="project_id[<?=$i?>]" type="checkbox" value="<?=$row->project_id?>" 
                            <?php
								$sql_ch = "SELECT project_id FROM team_to_project WHERE team_id = '".$team_id."' AND project_id = '".$row->project_id."' ";
								$c_cid = query($sql_ch);
								if ($c_cid = mysql_fetch_object(query($sql_ch))) echo "checked=\"checked\"";
								
                			?> />
                            <?=$row->title?>
                          </label>
                        </li>
        			<?php $i++; } ?>
				</ul>
			</dd>
		
           
		</dl>
            	
           </dl>
   					
			</form>    
            
            
        <script>
			  
			  $(document).ready(function(e) {
				   $("#tabs-ui").html('<?=$tabs?>');
						
				   $( "#tabs" ).tabs();
			  
			  });		
					
  		</script>
        
        </dl>
        
        <dl>
        
       
            
            
<?php
	controls($redirect, "#page_team_form_id");
	foot_admin(); 
?>